package com.example.netty.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
@Slf4j
public class FileAIO {
    public static void main(String[] args) throws IOException {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("test.txt"), StandardOpenOption.READ)) {
            //参数一   ByteBuffer
            //参数二   起始位置
            //参数三   附件
            //参数四   回调对象

            ByteBuffer byteBuffer = ByteBuffer.allocate(16);
            log.debug("read begin...");
            channel.read(byteBuffer, 0, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("read completion");
                    attachment.flip();
                    System.out.println(StandardCharsets.UTF_8.decode(attachment));
                    byteBuffer.flip();
                    System.out.println(StandardCharsets.UTF_8.decode(byteBuffer));
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.debug("read end...");
        System.in.read();
    }
}
